package com.joysuch.wwyt.bp.service.impl.script

import cn.hutool.http.HttpRequest
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.google.common.base.Strings
import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.google.gson.reflect.TypeToken
import com.joysuch.wwyt.bp.entity.BpDepart
import com.joysuch.wwyt.bp.entity.BpInspection
import com.joysuch.wwyt.bp.service.BpDepartService
import com.joysuch.wwyt.bp.service.IBpInspectionService
import com.joysuch.wwyt.core.bean.BpUserListBean
import com.joysuch.wwyt.core.common.util.JsonUtil
import com.joysuch.wwyt.core.entity.BaseConfig
import com.joysuch.wwyt.core.service.BaseConfigService
import com.joysuch.wwyt.core.service.BaseUserService
import com.joysuch.wwyt.core.support.Context
import com.joysuch.wwyt.util.ApplicationContextHolder

import javax.script.Invocable
import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
import java.text.SimpleDateFormat
import java.time.format.DateTimeFormatter
import java.util.stream.Collectors

String execute(BpInspection vo) {
    BaseConfigService baseConfigService = ApplicationContextHolder.getBean(BaseConfigService.class)
    IBpInspectionService bpInspectionService = ApplicationContextHolder.getBean(IBpInspectionService.class)

    StringBuilder sb = new StringBuilder()

    Map<String, String> result = new HashMap<>()

    String processKey = ""
    BaseConfig dangerProcessKey = baseConfigService.findConfig("quanyuanducha.hiddendanger.processkey");
    if (dangerProcessKey != null && !Strings.isNullOrEmpty(dangerProcessKey.getValue())) {
        processKey = dangerProcessKey.getValue()
    }
    String appid = "mvAmIwYJ7x6y0EADQvUb"
    String signature = "30ca19ac3d133b30b9243ed61646136f7818a3d85e6a70a3bfaa68d3d64566c3"
    String wfUrl = "http://127.0.0.1:8886"
    BaseConfig wfAddr = baseConfigService.findConfig("workflow.ip.address");
    if (wfAddr != null && !Strings.isNullOrEmpty(wfAddr.getValue())) {
        wfUrl = wfAddr.getValue()
    }

    Long tenantId = Context.currentTenantId
    String orgCode = Context.currentOrgCode
    Long userId = Context.currentUserId
    String userName = Context.getCurrentUser().getUsername()

    result.put("processDefKey", processKey)

    String defStr = HttpRequest.get(wfUrl + "/api/blade-workflow/process/getFormByProcessDefKey?processDefKey=" + processKey)
            .header("app-id", appid)
            .header("signature", signature)
            .header("tenant-id", tenantId.toString())
            .header("org-code", orgCode)
            .header("user-id", userId.toString())
            .header("user-name", userName)
            .timeout(10000)
            .execute()
            .body()

    JsonObject obj = new JsonParser().parse(defStr).getAsJsonObject()
    if (!obj.get("success").getAsBoolean()) {
        throw new RuntimeException("无法查询到全员督查隐患库配置，请联系技术人员解决")
    }
    String form = obj.get("data").getAsJsonObject().get("form").getAsString()
    Map<String, String> fieldLabelIdMap = new HashMap<>();

    String regular = "function convert(form){ return JSON.stringify(eval('(' + form + ')')) ;}";
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
    try {
        engine.eval(regular);
        Invocable invoke = (Invocable) engine;
        String formJson = invoke.invokeFunction("convert", form).toString();
        JsonObject formObj = new JsonParser().parse(formJson).getAsJsonObject();
        JsonArray groups = formObj.getAsJsonArray("group");
        Iterator<JsonElement> gIter = groups.iterator();
        while (gIter.hasNext()) {
            JsonObject group = gIter.next().getAsJsonObject();
            JsonArray columns = group.getAsJsonArray("column");
            Iterator<JsonElement> cIter = columns.iterator();
            while (cIter.hasNext()) {
                JsonObject field = cIter.next().getAsJsonObject();
                fieldLabelIdMap.put(field.get("label").getAsString(), field.get("prop").getAsString());
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("表单字符串解析异常！" + e.getMessage() + form)
    }

    String sftzdjs = fieldLabelIdMap.get("是否跳转到结束")
    String zllx = fieldLabelIdMap.get("治理类型")
    if (vo.getHiddenDangerStatus() == 1) {
        result.put(sftzdjs, "0")
        result.put("\$" + sftzdjs, "是")
        result.put(zllx, "0")
        result.put("\$" + zllx, "立即整改")
    } else {
        result.put(sftzdjs, "1")
        result.put("\$" + sftzdjs, "否")
        result.put(zllx, "1")
        result.put("\$" + zllx, "限期整改")
    }

    String sbry = fieldLabelIdMap.get("上报人员")
    result.put(sbry, vo.getCreateUserId().toString())
    result.put("\$" + sbry, vo.getCreateUserName())

    String sbbm = fieldLabelIdMap.get("上报部门")
    result.put(sbbm, vo.getCreateDeptId().toString())
    result.put("\$" + sbbm, vo.getCreateDeptName())

    String sbsj = fieldLabelIdMap.get("上报时间")
    result.put(sbsj, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(vo.getCreateTime()))

    String yhqy = fieldLabelIdMap.get("隐患区域")
    result.put(yhqy, vo.getDangerDistrictId().toString())
    result.put("\$" + yhqy, vo.getDangerDistrictName())

    String yhms = fieldLabelIdMap.get("隐患描述")
    result.put(yhms, vo.getDangerDesc())

    String zgbm = fieldLabelIdMap.get("整改部门")
    result.put(zgbm, vo.getCorrectionDepartId().toString())
    result.put("\$" + zgbm, vo.getCorrectionDepartName())

    String zgqx = fieldLabelIdMap.get("要求整改时间")
    result.put(zgqx, DateTimeFormatter.ofPattern("yyyy-MM-dd").format(vo.getDangerRequireDate()))

    Gson gson = new Gson();
    List<String> personIds = gson.fromJson(vo.getDangerCorrectionPersonId(), new TypeToken<List<String>>(){}.getType())
    String personIdStr = personIds.stream().collect(Collectors.joining(","))
    List<String> personNames = gson.fromJson(vo.getDangerCorrectionPersonName(), new TypeToken<List<String>>(){}.getType())
    String personNameStr = personNames.stream().collect(Collectors.joining(","))

    String zgbmfzr = fieldLabelIdMap.get("整改部门负责人")
    result.put(zgbmfzr, personIdStr)
    result.put("\$" + zgbmfzr, personNameStr)
    String zgfzr = fieldLabelIdMap.get("整改责任人")
    result.put(zgfzr, personIdStr)
    result.put("\$" + zgfzr, personNameStr)

    String yhjb = fieldLabelIdMap.get("隐患等级")
    result.put(yhjb, (Integer.parseInt(vo.getDangerLevel().substring(0, 1)) - 1) + "")
    result.put("\$" + yhjb, vo.getDangerLevel())

    String yhlx = fieldLabelIdMap.get("隐患类型")
    result.put(yhlx, vo.getDangerType())
    result.put("\$" + yhlx, vo.getDangerType())

    String yhly = fieldLabelIdMap.get("隐患来源")
    result.put(yhly, vo.getDangerSource())
    result.put("\$" + yhly, vo.getDangerSource())

    String zgqzp = fieldLabelIdMap.get("整改前照片")

    if (vo.getHiddenDangerStatus() == 1) {
        String zgry = fieldLabelIdMap.get("整改人员")
        result.put(zgry, personIdStr)
        result.put("\$" + zgry, personNameStr)

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd")
        String zgrq = fieldLabelIdMap.get("整改完成日期")
        result.put(zgrq, dtf.format(vo.getDangerRequireDate()))

        String zghzp = fieldLabelIdMap.get("整改后照片")

        String yzry = fieldLabelIdMap.get("验证人员")
        result.put(yzry, vo.getCreateUserId().toString())
        result.put("\$" + yzry, vo.getCreateUserName())

        String wcrq = fieldLabelIdMap.get("验证日期")
        result.put(wcrq, dtf.format(vo.getDangerFinishDate()))
    }

    String body = JsonUtil.toJson(result)
    sb.append("全员督查创建隐患参数：").append(body).append(";")
    String createRes = HttpRequest.post(wfUrl + "/api/blade-workflow/process/startProcessByKey")
            .header("app-id", appid)
            .header("signature", signature)
            .header("tenant-id", tenantId.toString())
            .header("org-code", orgCode)
            .header("user-id", userId.toString())
            .header("user-name", userName)
            .body(body)
            .timeout(10000)
            .execute()
            .body()
    sb.append("创建隐患接口返回：").append(createRes).append(";")
    JsonObject createResObj = new JsonParser().parse(createRes).getAsJsonObject()
    if (!createResObj.get("success").getAsBoolean()) {
        throw new RuntimeException("全员督查创建隐患参数失败，请联系技术人员解决" + sb.toString())
    }

    String processInstanceId = createResObj.get("data").getAsString()
    UpdateWrapper<BpInspection> update = new UpdateWrapper<>()
    update.set("hidden_danger_wfid", processInstanceId)
    update.eq("id", vo.getId())
    ((ServiceImpl) bpInspectionService).update(update)

    if (vo.getHiddenDangerStatus() == 1) {
        String getTaskIdRes = HttpRequest.post(wfUrl + "/api/blade-workflow/process/getProcessInstanceTaskId")
                .body("{\"processInstanceId\":\"" + processInstanceId + "\"}")
                .header("app-id", appid)
                .header("signature", signature)
                .header("tenant-id", tenantId.toString())
                .header("org-code", orgCode)
                .header("user-id", userId.toString())
                .header("user-name", userName)
                .timeout(10000)
                .execute()
                .body()
        sb.append("获取TaskID接口返回：").append(getTaskIdRes).append(";")
        JsonObject getTaskIdResObj = new JsonParser().parse(getTaskIdRes).getAsJsonObject()
        if (!getTaskIdResObj.get("success").getAsBoolean()) {
            throw new RuntimeException("获取TaskID参数失败，请联系技术人员解决" + sb.toString())
        }
        String taskId = getTaskIdResObj.get("data").getAsString()

        String getDetailRes = HttpRequest.get(wfUrl + "/api/blade-workflow/process/detail?taskId=" + taskId + "&processInsId=" + processInstanceId)
                .header("app-id", appid)
                .header("signature", signature)
                .header("tenant-id", tenantId.toString())
                .header("org-code", orgCode)
                .header("user-id", userId.toString())
                .header("user-name", userName)
                .timeout(10000)
                .execute()
                .body()
        sb.append("获取TaskDetail接口返回：").append(getDetailRes).append(";")
        JsonObject detailResObj = new JsonParser().parse(getDetailRes).getAsJsonObject()
        if (!detailResObj.get("success").getAsBoolean()) {
            throw new RuntimeException("获取TaskDetail参数失败，请联系技术人员解决" + sb.toString())
        }
        JsonObject processObj = detailResObj.get("data").getAsJsonObject().get("process").getAsJsonObject()

        JsonObject completeTask = new JsonObject()
        completeTask.addProperty("taskId", taskId)
        completeTask.addProperty("processInstanceId", processInstanceId)
        completeTask.addProperty("pass", true)
        completeTask.addProperty("comment", "auto complete")
        completeTask.add("processDefinitionName", processObj.get("processDefinitionName"))
        completeTask.add("processDefinitionId", processObj.get("processDefinitionId"))
        completeTask.add("variables", processObj.get("variables"))

        String completeTaskBody = completeTask.toString()
        sb.append("CompleteTask参数:").append(completeTaskBody)
        String completeTaskRes = HttpRequest.post(wfUrl + "/api/blade-workflow/process/completeTask")
                .body(completeTaskBody)
                .header("app-id", appid)
                .header("signature", signature)
                .header("tenant-id", tenantId.toString())
                .header("org-code", orgCode)
                .header("user-id", userId.toString())
                .header("user-name", userName)
                .timeout(10000)
                .execute()
                .body()
        sb.append("CompleteTask接口返回：").append(completeTaskRes).append(";")
        JsonObject completeTaskResObj = new JsonParser().parse(completeTaskRes).getAsJsonObject()
        if (!completeTaskResObj.get("success").getAsBoolean()) {
            throw new RuntimeException("CompleteTask参数失败，请联系技术人员解决" + sb.toString())
        }
    }

    return sb.toString()
}